package org.jeecg.modules.yc.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.compress.utils.Lists;
import org.jeecg.modules.yc.NB.Model.YCAnalysisModel;
import org.jeecg.modules.yc.NB.protocol.YCAnalysis;
import org.jeecg.modules.yc.util.TransformationTool;
import org.jeecg.modules.yc.web.entity.DeviceReport;
import org.jeecg.modules.yc.web.entity.HourTimeLine;
import org.jeecg.modules.yc.web.entity.vo.HourTimeExportXls;
import org.jeecg.modules.yc.web.mapper.DeviceReportMapper;
import org.jeecg.modules.yc.web.service.IDeviceReportService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description: 上报数据
 * @Author: jeecg-boot
 * @Date:   2023-12-26
 * @Version: V1.0
 */
@Service
public class DeviceReportServiceImpl extends ServiceImpl<DeviceReportMapper, DeviceReport> implements IDeviceReportService {

    @Override
    public HourTimeLine deviceHourTimeLineData(QueryWrapper<DeviceReport> queryWrapper) {
        List<DeviceReport> pageList = this.list(queryWrapper);
        HourTimeLine hourTimeLine = new HourTimeLine();
        pageList.forEach(v -> {
            YCAnalysisModel model = YCAnalysis.analysis(TransformationTool.hexStringBytes(v.getMetadata(),0,0));
            byte[] hexData = model.getDataArea();
            // 假设你已经有了一个Date对象
            Date initialDate = v.getCreateTime(); // 这里只是为了示例，你可以替换为任何已有的Date对象
            String voltage = String.valueOf((float)((hexData[hexData.length - 4] & 0xFF) << 8 | (hexData[hexData.length - 3] & 0xFF))/1000);
            // 创建一个Calendar实例，并设置为初始Date的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(initialDate);
            // 将时间往前推 1 个小时
            // Calendar.HOUR_OF_DAY 表示使用 24 小时制
            calendar.add(Calendar.HOUR_OF_DAY, -1);
            // 每两个字节表示一个温度数据，紧接着的两个字节表示一个湿度数据
            for (int i = 0; i < hexData.length - 4; i += 4) {
                // 检查是否还有足够的字节来读取温度和湿度
                if (i + 3 < hexData.length) {
                    // 提取温度数据（两个字节）
                    int temp = (hexData[i] & 0xFF) << 8 | (hexData[i + 1] & 0xFF);
                    // 提取湿度数据（两个字节）
                    int DB = (hexData[i + 2] & 0xFF) << 8 | (hexData[i + 3] & 0xFF);
                    int reference = (hexData[hexData.length - 2] & 0xFF) << 8 | (hexData[hexData.length - 1] & 0xFF);
                    String maxDBStr = String.format("%.2f", DBMath(DB,reference));
                    hourTimeLine.getPdMax().add(maxDBStr);
                    hourTimeLine.getTemperatureMax().add(String.valueOf(temp/10));
                    // 添加3分钟
                    calendar.add(Calendar.MINUTE, 3);
                    // 获取更新后的Date对象
                    Date updatedDate = calendar.getTime();
                    hourTimeLine.getCreateTime().add(updatedDate);
                    hourTimeLine.getVoltage().add(voltage);
                }
            }
        });

        return hourTimeLine;
    }


    @Override
    public List<HourTimeExportXls> HourTimeExportXls(QueryWrapper<DeviceReport> queryWrapper) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<DeviceReport> pageList = this.list(queryWrapper);
        List<HourTimeExportXls> hourTimeLineList = Lists.newArrayList();
        pageList.forEach(v -> {

            YCAnalysisModel model = YCAnalysis.analysis(TransformationTool.hexStringBytes(v.getMetadata(),0,0));
            assert model != null;
            byte[] hexData = model.getDataArea();
            // 假设你已经有了一个Date对象
            Date initialDate = v.getCreateTime(); // 这里只是为了示例，你可以替换为任何已有的Date对象
            String voltage = String.valueOf((float)((hexData[hexData.length - 4] & 0xFF) << 8 | (hexData[hexData.length - 3] & 0xFF))/1000);
            // 创建一个Calendar实例，并设置为初始Date的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(initialDate);
            // 每两个字节表示一个温度数据，紧接着的两个字节表示一个湿度数据
            for (int i = 0; i < hexData.length - 4; i += 4) {

                // 检查是否还有足够的字节来读取温度和湿度
                if (i + 3 < hexData.length) {
                    HourTimeExportXls hourTimeExportXls = new HourTimeExportXls();
                    // 提取温度数据（两个字节）
                    int temp = (hexData[i] & 0xFF) << 8 | (hexData[i + 1] & 0xFF);
                    // 提取湿度数据（两个字节）
                    int DB = (hexData[i + 2] & 0xFF) << 8 | (hexData[i + 3] & 0xFF);
                    int reference = (hexData[hexData.length - 2] & 0xFF) << 8 | (hexData[hexData.length - 1] & 0xFF);
                    String maxDBStr = String.format("%.2f", DBMath(DB,reference));
                    hourTimeExportXls.setPdMax(maxDBStr);
                    hourTimeExportXls.setTemperatureMax(String.valueOf(temp/10));
                    // 添加3分钟
                    calendar.add(Calendar.MINUTE, 3);
                    // 获取更新后的Date对象
                    Date updatedDate = calendar.getTime();
                    hourTimeExportXls.setCreateTime(format.format(updatedDate));
                    hourTimeExportXls.setVoltage(voltage);
                    hourTimeExportXls.setDeviceNo(pageList.get(0).getDeviceNo());
                    hourTimeExportXls.setDeviceName(pageList.get(0).getDeviceName());
                    hourTimeExportXls.setTerminalName(pageList.get(0).getTerminalName());
                    hourTimeExportXls.setTerminalNo(pageList.get(0).getTerminalNo());
                    hourTimeLineList.add(hourTimeExportXls);
                }
            }
        });

        return hourTimeLineList;
    }
    private double DBMath(int db,int reference){
        if(db <= reference ){
            return 0;
        }
        float dbMath = ((float) db)-((float)reference);
        return 20*Math.log10(dbMath);
    }
}
